package com.tmall.wireless.virtualviewdemo.slice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tmall.wireless.vaf.Log;
import com.tmall.wireless.vaf.expr.engine.utils.Toast;
import com.tmall.wireless.vaf.framework.VafContext;
import com.tmall.wireless.vaf.framework.ViewManager;
import com.tmall.wireless.vaf.virtualview.core.IContainer;
import com.tmall.wireless.vaf.virtualview.core.Layout;
import com.tmall.wireless.vaf.virtualview.event.EventData;
import com.tmall.wireless.vaf.virtualview.event.EventManager;
import com.tmall.wireless.vaf.virtualview.event.IEventProcessor;
import com.tmall.wireless.virtualviewdemo.MyApplication;
import com.tmall.wireless.virtualviewdemo.PreviewData;
import com.tmall.wireless.virtualviewdemo.ResourceTable;
import com.tmall.wireless.virtualviewdemo.utils.HttpUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.Text;
import ohos.agp.utils.TextTool;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Locale;

public class PreviewActivityAbilitySlice extends AbilitySlice implements Component.ClickedListener {

    private static final String TAG = "VvPreview";

    private static final String KEY_DIR = "key_dir";
    private static final String KEY_NAME = "key_name";
    private static final String KEY_URL = "key_url";
    public static final String KEY_FROM = "key_from";
    private static final int FROM_SCAN = 1;
    public static final int FROM_REAL_PREVIEW = 2;

    private VafContext sVafContext;
    private ViewManager sViewManager;

    private DirectionalLayout mLinearLayout;
    private Text mTvTitle;
    private Component mContainer;

    protected String mTemplateName;
    protected JSONObject mJsonData;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_preview_activity);

        mLinearLayout = (DirectionalLayout) findComponentById(ResourceTable.Id_container);
        mTvTitle = (Text) findComponentById(ResourceTable.Id_title);
        findComponentById(ResourceTable.Id_tv_refresh).setClickedListener(this);
        findComponentById(ResourceTable.Id_tv_rtl).setClickedListener(this);

        sVafContext = MyApplication.getInstance().getVafContext();
        sViewManager = MyApplication.getInstance().getViewManager();

        sVafContext.getEventManager().register(EventManager.TYPE_Click, new IEventProcessor() {
            @Override
            public boolean process(EventData data) {
                Log.d(TAG, "TYPE_Click data view:" + data.mView);
                Log.d(TAG, "TYPE_Click view name:" + data.mVB.getTag("name"));
                Log.d(TAG, "TYPE_Click view traceId:" + data.mVB.getTag("activityTraceId"));
                Toast.showShort(PreviewActivityAbilitySlice.this, "TYPE_Click view name:" + data.mVB.getTag("name")
                        + "\n traceId:" + data.mVB.getTag("activityTraceId"));
                return true;
            }
        });

        sVafContext.getEventManager().register(EventManager.TYPE_Exposure, new IEventProcessor() {
            @Override
            public boolean process(EventData data) {
                Log.d(TAG, "TYPE_Exposure data view:" + data.mView);
                Log.d(TAG, "TYPE_Exposure view name:" + data.mVB.getTag("name"));
                Log.d(TAG, "TYPE_Exposure view traceId:" + data.mVB.getTag("activityTraceId"));
//                    Toast.makeText(PreviewActivity.this,
//                            "TYPE_Exposure view name:" + data.mVB.getTag("name")
//                                    + "traceId:" + data.mVB.getTag("activityTraceId"), Toast.LENGTH_SHORT).show();
                return true;
            }
        });


    }

    @Override
    public void onActive() {
        super.onActive();
        Intent intent = getAbility().getIntent();
        if (FROM_SCAN == intent.getIntParam(KEY_FROM, 0)) {
            String url = intent.getStringParam(KEY_URL);
            mTemplateName = HttpUtil.getFirstPath(url);
            refreshByUrl(url);
        } else if (FROM_REAL_PREVIEW == intent.getIntParam(KEY_FROM, 0)) {
            mTemplateName = intent.getStringParam(KEY_NAME);
            refreshByName(mTemplateName);
        }
        setTitle(mTemplateName);
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    protected void preview(String templateName, JSONObject jsonData) {
        if (TextTool.isNullOrEmpty(templateName)) {
            Log.e(TAG, "Template name should not be empty!!!!");
            return;
        }
        mContainer = sVafContext.getContainerService().getContainer(templateName, true);
        IContainer iContainer = (IContainer) mContainer;
        String viewType = iContainer.getVirtualView().getViewType();
        Log.i("viewType " + viewType);
        if (jsonData != null) {
            iContainer.getVirtualView().setVData(jsonData);
        }

        Layout.Params p = iContainer.getVirtualView().getComLayoutParams();
        DirectionalLayout.LayoutConfig marginLayoutParams = new DirectionalLayout.LayoutConfig(p.mLayoutWidth, p.mLayoutHeight);
        Log.i("PreviewActivityAbilitySlice.preview([templateName, jsonData]):132       " + p.mLayoutWidth + "               " + p.mLayoutHeight);
        marginLayoutParams.setMarginLeft(p.mLayoutMarginLeft);
        marginLayoutParams.setMarginTop(p.mLayoutMarginTop);
        marginLayoutParams.setMarginRight(p.mLayoutMarginRight);
        marginLayoutParams.setMarginBottom(p.mLayoutMarginBottom);
//        ShapeElement shapeElement = new ShapeElement();
//        shapeElement.setRgbColor(new RgbColor(250,0,0));
//        mContainer.setBackground(shapeElement);
        mLinearLayout.removeAllComponents();
        mLinearLayout.addComponent(mContainer, marginLayoutParams);
    }

    protected void setTitle(String title) {
        if (!TextTool.isNullOrEmpty(title)) {
            mTvTitle.setText(title);
        }
    }

    @Override
    public void onClick(Component component) {
        int id = component.getId();
        if (id == ResourceTable.Id_tv_refresh) {
            Intent intent = getAbility().getIntent();
            if (FROM_SCAN == intent.getIntParam(KEY_FROM, 0)) {
                String url = intent.getStringParam(KEY_URL);
                mTemplateName = HttpUtil.getFirstPath(url);
                refreshByUrl(url);
            } else if (FROM_REAL_PREVIEW == intent.getIntParam(KEY_FROM, 0)) {
                mTemplateName = intent.getStringParam(KEY_NAME);
                refreshByName(mTemplateName);
            }
        } else if (id == ResourceTable.Id_tv_rtl) {
            changeRtl();
        }
    }

    private void refreshByName(String name) {
        if (!TextTool.isNullOrEmpty(name)) {
            refreshByUrl(getUrl(name));
        }
    }


    private void changeRtl() {
        // simulate rtl locale
        if ("ar".equalsIgnoreCase(Locale.getDefault().getLanguage())) {
            Locale locale = new Locale("en");
            Locale.setDefault(locale);
        } else {
            Locale locale = new Locale("ar");
            Locale.setDefault(locale);
        }
        preview(mTemplateName, mJsonData);
    }

    private String getUrl(String name) {
        return HttpUtil.getHostUrl() + name + "/data.json";
    }

    private void loadTemplates(ArrayList<String> templates) {
        for (String temp : templates) {
            //  sViewManager.loadBinBufferSync(Base64.decode(temp, Base64.DEFAULT));
            sViewManager.loadBinBufferSync(Base64.getDecoder().decode(temp));
        }
    }

    private void refreshByUrl(final String url) {
        new Thread(() -> {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(url)
                    .build();
            try {
                Response response = client.newCall(request).execute();
                if (response != null && response.isSuccessful()) {
                    if (response.body() != null) {
                        String string = response.body().string();
                        final PreviewData previewData = JSON.parseObject(string, PreviewData.class);
                        if (previewData != null) {
                            loadTemplates(previewData.templates);
                        }
                        getUITaskDispatcher().syncDispatch(() -> {
                            JSONObject json = previewData.data;
                            if (json != null) {
                                try {
                                    mJsonData = JSON.parseObject(json.toString());
                                    preview(mTemplateName, mJsonData);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }
}
